/**
 * Copyright (c) 2024 Huawei Technologies Co., Ltd.
 * This file is a part of the CANN Open Software.
 * Licensed under CANN Open Software License Agreement Version 1.0 (the "License").
 * Please refer to the License for details. You may not use this file except in compliance with the License.
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
 * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
 * See LICENSE in the root of the software repository for the full text of the License.
 */

#include "../../../common/data_utils.h"
#ifndef ASCENDC_CPU_DEBUG
#include "acl/acl.h"
extern void softmaxgrad_custom_do(uint32_t coreDim, void* l2ctrl, void* stream, uint8_t* x, uint8_t* y, uint8_t* z,
    uint8_t* workspace, uint8_t* tiling);
#else
#include "tikicpulib.h"
extern "C" __global__ __aicore__ void softmaxgrad_custom(GM_ADDR x, GM_ADDR y, GM_ADDR z, GM_ADDR workspace,
    GM_ADDR tiling);
#endif

constexpr uint32_t ROW_NUM = 960;
constexpr uint32_t COLUMN_NUM = 960;
constexpr uint32_t USED_CORE_NUM = 40;
constexpr uint32_t WORKSPACE_SIZE = 1024;
constexpr uint32_t TILINGDATA_SIZE = 28;  // Element count of struct SoftmaxgradCustomTilingData
constexpr uint32_t FLOAT_NUM_PER_BLOCK = 8;

extern void GenerateTiling(const uint32_t m, const uint32_t k, const uint32_t coreNum, const uint32_t tilingSize,
                           uint8_t* tilingData);

static int64_t CompareResult(void* outputData, const int64_t outSize)
{
    void* goldenData;
#ifdef ASCENDC_CPU_DEBUG
    goldenData = (uint8_t*)AscendC::GmAlloc(outSize);
#else
    CHECK_ACL(aclrtMallocHost((void**)(&goldenData), outSize));
#endif
    size_t goldenSize = outSize;
    bool ret = ReadFile("../output/golden.bin", goldenSize, goldenData, goldenSize);
    if (ret) {
        printf("ReadFile golden success!\n");
    } else {
#ifdef ASCENDC_CPU_DEBUG
        AscendC::GmFree((void*)goldenData);
#else
        CHECK_ACL(aclrtFreeHost(goldenData));
#endif
        return -1;
    }
    constexpr float EPS = 1e-5;
    int64_t wrongNum = 0;

    for (int i = 0; i < outSize / sizeof(float); i++) {
        float a = ((float*)outputData)[i];
        float b = ((float*)goldenData)[i];
        float ae = std::abs(a - b);
        float re = ae / abs(b);
        if (ae > EPS && re > EPS) {
            printf("CompareResult failed output is %lf, golden is %lf\n", a, b);
            wrongNum++;
        }
    }
#ifdef ASCENDC_CPU_DEBUG
    AscendC::GmFree((void*)goldenData);
#else
    CHECK_ACL(aclrtFreeHost(goldenData));
#endif
    return wrongNum;
}

int32_t main(int32_t argc, char* argv[])
{
    size_t xSize = ROW_NUM * ROW_NUM * sizeof(float);
    size_t workspaceSize = WORKSPACE_SIZE * sizeof(float);
    size_t tilingSize = TILINGDATA_SIZE * sizeof(uint32_t);  // tilingData size , defined in softmax_custom_tiling.h
    size_t ySize = ROW_NUM * ROW_NUM * sizeof(float);
    size_t zSize = ROW_NUM * ROW_NUM * sizeof(float);
    int64_t wrongNum = -1;
#ifdef ASCENDC_CPU_DEBUG
    uint8_t* x = (uint8_t*)AscendC::GmAlloc(xSize);
    uint8_t* y = (uint8_t*)AscendC::GmAlloc(ySize);
    uint8_t* z = (uint8_t*)AscendC::GmAlloc(zSize);
    uint8_t* workspace = (uint8_t*)AscendC::GmAlloc(workspaceSize);
    uint8_t* tiling = (uint8_t*)AscendC::GmAlloc(tilingSize);

    ReadFile("../input/input_x.bin", xSize, x, xSize);
    ReadFile("../input/input_y.bin", ySize, y, ySize);
    ReadFile("../input/workspace.bin", workspaceSize, workspace, workspaceSize);
    GenerateTiling(ROW_NUM, COLUMN_NUM, USED_CORE_NUM, tilingSize, tiling);

    AscendC::SetKernelMode(KernelMode::AIV_MODE);                                // run in aiv mode
    ICPU_RUN_KF(softmaxgrad_custom, USED_CORE_NUM, x, y, z, workspace, tiling);  // use this macro for cpu debug

    WriteFile("../output/output_z.bin", z, zSize);
    wrongNum = CompareResult(z, zSize);

    AscendC::GmFree((void*)x);
    AscendC::GmFree((void*)y);
    AscendC::GmFree((void*)z);
    AscendC::GmFree((void*)workspace);
    AscendC::GmFree((void*)tiling);
#else
    // Initialize resources
    CHECK_ACL(aclInit(nullptr));
    aclrtContext context;
    int32_t deviceId = 0;
    CHECK_ACL(aclrtSetDevice(deviceId));
    CHECK_ACL(aclrtCreateContext(&context, deviceId));
    aclrtStream stream = nullptr;
    CHECK_ACL(aclrtCreateStream(&stream));

    uint8_t *xHost, *zHost, *yHost, *workspaceHost, *tilingHost;
    uint8_t *xDevice, *zDevice, *yDevice, *workspaceDevice, *tilingDevice;

    // Allocate host memory and device memory
    CHECK_ACL(aclrtMallocHost((void**)(&xHost), xSize));
    CHECK_ACL(aclrtMallocHost((void**)(&yHost), ySize));
    CHECK_ACL(aclrtMallocHost((void**)(&zHost), zSize));
    CHECK_ACL(aclrtMallocHost((void**)(&workspaceHost), workspaceSize));
    CHECK_ACL(aclrtMallocHost((void**)(&tilingHost), tilingSize));

    CHECK_ACL(aclrtMalloc((void**)&xDevice, xSize, ACL_MEM_MALLOC_HUGE_FIRST));
    CHECK_ACL(aclrtMalloc((void**)&yDevice, ySize, ACL_MEM_MALLOC_HUGE_FIRST));
    CHECK_ACL(aclrtMalloc((void**)&zDevice, zSize, ACL_MEM_MALLOC_HUGE_FIRST));
    CHECK_ACL(aclrtMalloc((void**)&workspaceDevice, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST));
    CHECK_ACL(aclrtMalloc((void**)&tilingDevice, tilingSize, ACL_MEM_MALLOC_HUGE_FIRST));

    ReadFile("../input/input_x.bin", xSize, xHost, xSize);
    ReadFile("../input/input_y.bin", ySize, yHost, ySize);
    ReadFile("../input/workspace.bin", workspaceSize, workspaceHost, workspaceSize);

    GenerateTiling(ROW_NUM, COLUMN_NUM, USED_CORE_NUM, tilingSize, tilingHost);

    // Copy host memory to device memory
    CHECK_ACL(aclrtMemcpy(xDevice, xSize, xHost, xSize, ACL_MEMCPY_HOST_TO_DEVICE));
    CHECK_ACL(aclrtMemcpy(yDevice, ySize, yHost, ySize, ACL_MEMCPY_HOST_TO_DEVICE));
    CHECK_ACL(aclrtMemcpy(workspaceDevice, workspaceSize, workspaceHost, workspaceSize, ACL_MEMCPY_HOST_TO_DEVICE));
    CHECK_ACL(aclrtMemcpy(tilingDevice, tilingSize, tilingHost, tilingSize, ACL_MEMCPY_HOST_TO_DEVICE));

    // Execute the kernel
    softmaxgrad_custom_do(USED_CORE_NUM, nullptr, stream, xDevice, yDevice, zDevice, workspaceDevice, tilingDevice);

    // Wait for the stop event to complete
    CHECK_ACL(aclrtSynchronizeStream(stream));

    // Copy result to host memory and write to output file
    CHECK_ACL(aclrtMemcpy(zHost, zSize, zDevice, zSize, ACL_MEMCPY_DEVICE_TO_HOST));
    WriteFile("../output/output_z.bin", zHost, zSize);

    // Compare the result with the golden result
    wrongNum = CompareResult(zHost, zSize);

    // Clean up memory
    CHECK_ACL(aclrtFree(xDevice));
    CHECK_ACL(aclrtFree(zDevice));
    CHECK_ACL(aclrtFree(yDevice));
    CHECK_ACL(aclrtFree(workspaceDevice));
    CHECK_ACL(aclrtFree(tilingDevice));
    CHECK_ACL(aclrtFreeHost(xHost));
    CHECK_ACL(aclrtFreeHost(zHost));
    CHECK_ACL(aclrtFreeHost(yHost));
    CHECK_ACL(aclrtFreeHost(workspaceHost));
    CHECK_ACL(aclrtFreeHost(tilingHost));

    CHECK_ACL(aclrtDestroyStream(stream));
    CHECK_ACL(aclrtDestroyContext(context));
    CHECK_ACL(aclrtResetDevice(deviceId));
    CHECK_ACL(aclFinalize());
#endif
    if (wrongNum != 0) {
        printf("test failed!\n");
    } else {
        printf("test pass!\n");
    }
    return 0;
}
